package com.jsean.demo;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Properties;

@Slf4j
public class BloomFilterDemo {
    final static String GUAVA = "Guava";

    public static void main(String[] args) {
        String filterType = getFilterType();

        switch (filterType) {
            case GUAVA:
                GuavaBloomFilter();
                break;
            default:
                log.error("not support");
        }
    }

    private static String getFilterType() {
        Properties props = new Properties();
        try (InputStream is = BloomFilterDemo.class.getClassLoader().getResourceAsStream("application.properties")) {
            props.load(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String filterType = props.getProperty("app.filter");
        return filterType;
    }

    private static void GuavaBloomFilter() {
        BloomFilter<String> bloomFilter = BloomFilter.create(
                Funnels.stringFunnel(Charset.defaultCharset()),  // 指定存储类型（这里是String）
                1_000_000,               // 预计元素数量
                0.01                     // 误判率（1%）
        );

        // 添加元素
        bloomFilter.put("apple");
        bloomFilter.put("banana");
        bloomFilter.put("orange");

        // 判断元素是否存在
        log.info("{}", bloomFilter.mightContain("apple"));   // true（可能存在）
        log.info("{}", bloomFilter.mightContain("grape"));   // false（绝对不存在）
    }
}